import Cookies from "js-cookie";
import store from "../store";
import { getAdminInfo } from "../request/http";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

const routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/Login.vue"),
  },
];
const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

// 函数封装
const genRoute = () => {
  // 动态添加路由
  // 获取vuex 里面的menus 数据
  const menus = store.getters.genNewMenus;
  for (let key in menus) {
    // key 就是对象的键
    // console.log(key);

    // 一级菜单对象
    // 每一次遍历的路由规则
    let routeObj: RouteRecordRaw = {
      path: "/" + menus[key].name,
      name: menus[key].name,
      component: () => import("../views/Home/home.vue"),
      children: [],
    };

    // 二级菜单
    for (let i = 0; i < menus[key].children.length; i++) {
      routeObj.children!.push({
        path: menus[key].children[i].name,
        name: menus[key].children[i].name,
        component: () =>
          import(
            `../views/${menus[key].name}/${menus[key].children[i].name}.vue`
          ),
      });
    }
    router.addRoute(routeObj);
  }
  router.addRoute({
    path: "/",
    name: "home",
    redirect: "/index",
    component: () => import("../views/Home/home.vue"),
    children: [
      {
        path: "index",
        name: "index",
        component: () => import("../views/index/index.vue"),
      },
    ],
  });
};

// 刷新首页   解决vuex数据消失
// 前置导航守卫
router.beforeEach(async (to, from, next) => {
  // console.log(to);
  // console.log(from);

  // 什么时候发送数据请求  登录后有token+vuex没有数据
  const token = Cookies.get("token");
  if (token && store.state.menus.length === 0) {
    // let res = await getAdminInfo();
    // if (res.code === 200) {
    //   // 存储数据到vuex
    //   store.commit("updateMenus", res.data.menus);
    //   genRoute();
    // }
    // 将上面的代码封装到actions
    await store.dispatch("getAdminInfo");
    genRoute();
    next(to);
  } else if (
    token &&
    store.getters.genNewMenus &&
    to.path === "/home" &&
    from.path === "/login"
  ) {
    genRoute();
    next("/index");
  } else if (!token && to.path !== "/login") {
    next("/login");
  } else if (token && to.path === "/login") {
    next(from);
  } else {
    next();
  }
});

export default router;
